<?php
namespace Home\Controller;
use Common\Controller\CommonController;

/**
 * 直播类
 * @author 张亚伟 <zhangyw@zhijin101.com>
 */
class LiveVideoController extends CommonController
{
    public function index()
    {
        $model = M('LiveVideo');
		$Count = $model->count();
		$Page = new \Think\Pager($Count,10);
		$show = $Page->showhtml();
		$keyword = I('keyword');
		$where = [];
		if(!empty($keyword)){
			$where['title'] = array('like',"%".$keyword."%");
		}
		$list = $model->where($where)->limit($Page->firstRow.','.$Page->listRows)->order('sort asc,id desc')->select();
		if($list){
			foreach($list as $key=>&$row){
				$row['cover'] = json_decode($row['cover'], true);
				$row['cover'] = isset($row['cover']['0']) ? $row['cover'][0]:'';
				$row['status'] = $row['status'] ? '直播中' : '未直播';
				$row['is_show'] = $row['is_show'] ? '是' : '否';
			}
		}
		$this->assign('page',$show);
		$this -> assign('list', $list);
		$this -> display();
    }

    public function add()
    {
		if(IS_POST){
			$data = I('post.');
			$data['cover'] = json_encode($data['cover']);
			$id = M('LiveVideo')->add($data);
			if($id){
				$this->ajaxReturn(array('s'=>true,'m'=>'添加成功', 'url'=>U('index')));
			}else{
				$this->ajaxReturn(array('s'=>false,'m'=>'添加失败!'));
			}
		}else{
			$this -> display();
		}
    }

    public function edit()
    {
		$id = I('id');
        if(IS_POST){
			$data = I('post.');
			$data['cover'] = json_encode($data['cover']);
			$res = M('LiveVideo')->where(['id'=>$id])->save($data);
			if($res!==false){
				$this->ajaxReturn(array('s'=>true,'m'=>'修改成功', 'url'=>U('index')));
			}else{
				$this->ajaxReturn(array('s'=>false,'m'=>'修改失败!'));
			}
		}else{
			$info = M('LiveVideo')->where(['id'=>$id])->find();
			$info['cover'] = json_decode($info['cover'], true);
			$this -> assign('info', $info);
			$this -> display();
		}
    }

    public function delete()
    {
		$id = I('id');
        $res = M('LiveVideo')->where(['id'=>$id])->delete();
		if ($res!==false) {
			$this -> redirect('index');
		}
    }
}
